package process

import (
	"fmt"
	"strings"
)

// ProcessGroup 进程组
type ProcessGroup struct {
	Name         string   `json:"name"`          // 进程组名称
	Members      []string `json:"members"`       // 组成员列表
	Pattern      string   `json:"pattern"`       // 模式（如 DEMO%d）
	Start        int      `json:"start"`         // 起始编号
	End          int      `json:"end"`           // 结束编号
	Enabled      bool     `json:"enabled"`       // 是否启用
	GroupMembers []string `json:"group_members"` // 手动指定的组成员
	RestartCmd   string   `json:"restart_cmd"`   // 重启命令
	WorkDir      string   `json:"work_dir"`      // 工作目录
	Env          []string `json:"env"`           // 环境变量
}

// ProcessGroupStatus 进程组状态
type ProcessGroupStatus struct {
	GroupName     string                `json:"group_name"`
	TotalMembers  int                   `json:"total_members"`
	RunningCount  int                   `json:"running_count"`
	StoppedCount  int                   `json:"stopped_count"`
	ErrorCount    int                   `json:"error_count"`
	Members       []ProcessMemberStatus `json:"members"`
	OverallStatus string                `json:"overall_status"` // healthy, warning, critical
}

// ProcessMemberStatus 进程组成员状态
type ProcessMemberStatus struct {
	Name    string  `json:"name"`
	Running bool    `json:"running"`
	PID     int32   `json:"pid"`
	CPU     float64 `json:"cpu"`
	Memory  float64 `json:"memory"`
	Status  string  `json:"status"`
	Error   string  `json:"error,omitempty"`
}

// ProcessGroupManager 进程组管理器
type ProcessGroupManager struct {
	groups map[string]*ProcessGroup
}

// NewProcessGroupManager 创建进程组管理器
func NewProcessGroupManager() *ProcessGroupManager {
	return &ProcessGroupManager{
		groups: make(map[string]*ProcessGroup),
	}
}

// AddGroup 添加进程组
func (pgm *ProcessGroupManager) AddGroup(group *ProcessGroup) {
	pgm.groups[group.Name] = group
}

// GetGroup 获取进程组
func (pgm *ProcessGroupManager) GetGroup(name string) *ProcessGroup {
	return pgm.groups[name]
}

// GetAllGroups 获取所有进程组
func (pgm *ProcessGroupManager) GetAllGroups() map[string]*ProcessGroup {
	return pgm.groups
}

// GenerateGroupMembers 生成进程组成员列表
func (pgm *ProcessGroupManager) GenerateGroupMembers(group *ProcessGroup) []string {
	var members []string

	if len(group.GroupMembers) > 0 {
		// 使用手动指定的成员
		members = group.GroupMembers
	} else if group.Pattern != "" && group.Start > 0 && group.End > 0 {
		// 使用模式生成成员
		for i := group.Start; i <= group.End; i++ {
			memberName := strings.ReplaceAll(group.Pattern, "%d", fmt.Sprintf("%d", i))
			members = append(members, memberName)
		}
	}

	return members
}

// CheckGroupStatus 检查进程组状态
func (pgm *ProcessGroupManager) CheckGroupStatus(groupName string, monitor *ProcessMonitor) (*ProcessGroupStatus, error) {
	group, exists := pgm.groups[groupName]
	if !exists {
		return nil, fmt.Errorf("进程组 %s 不存在", groupName)
	}

	// 生成成员列表
	members := pgm.GenerateGroupMembers(group)
	if len(members) == 0 {
		return nil, fmt.Errorf("进程组 %s 没有成员", groupName)
	}

	status := &ProcessGroupStatus{
		GroupName:    groupName,
		TotalMembers: len(members),
		Members:      make([]ProcessMemberStatus, 0, len(members)),
	}

	runningCount := 0
	stoppedCount := 0
	errorCount := 0

	// 检查每个成员的状态
	for _, memberName := range members {
		memberStatus := ProcessMemberStatus{
			Name: memberName,
		}

		// 检查进程是否运行
		info, err := monitor.CheckProcessByName(memberName)
		if err != nil {
			memberStatus.Status = "error"
			memberStatus.Error = err.Error()
			errorCount++
		} else if info.Running {
			memberStatus.Running = true
			memberStatus.PID = info.PID
			memberStatus.CPU = info.CPU
			memberStatus.Memory = info.Memory
			memberStatus.Status = "running"
			runningCount++
		} else {
			memberStatus.Status = "stopped"
			stoppedCount++
		}

		status.Members = append(status.Members, memberStatus)
	}

	status.RunningCount = runningCount
	status.StoppedCount = stoppedCount
	status.ErrorCount = errorCount

	// 确定整体状态
	if errorCount > 0 {
		status.OverallStatus = "critical"
	} else if stoppedCount > 0 {
		status.OverallStatus = "warning"
	} else {
		status.OverallStatus = "healthy"
	}

	return status, nil
}

// GetGroupSummary 获取进程组摘要
func (pgm *ProcessGroupManager) GetGroupSummary(groupName string) string {
	group, exists := pgm.groups[groupName]
	if !exists {
		return fmt.Sprintf("进程组 %s 不存在", groupName)
	}

	members := pgm.GenerateGroupMembers(group)
	if len(members) == 0 {
		return fmt.Sprintf("进程组 %s 没有成员", groupName)
	}

	return fmt.Sprintf("进程组 %s 包含 %d 个成员: %s",
		groupName, len(members), strings.Join(members, ", "))
}

// ValidateGroup 验证进程组配置
func (pgm *ProcessGroupManager) ValidateGroup(group *ProcessGroup) error {
	if group.Name == "" {
		return fmt.Errorf("进程组名称不能为空")
	}

	if len(group.GroupMembers) == 0 && (group.Pattern == "" || group.Start <= 0 || group.End <= 0) {
		return fmt.Errorf("进程组 %s 必须指定 group_members 或 group_pattern+group_start+group_end", group.Name)
	}

	if group.Pattern != "" && group.Start > group.End {
		return fmt.Errorf("进程组 %s 的起始编号不能大于结束编号", group.Name)
	}

	return nil
}

// GetGroupMemberNames 获取进程组成员名称列表
func (pgm *ProcessGroupManager) GetGroupMemberNames(groupName string) ([]string, error) {
	group, exists := pgm.groups[groupName]
	if !exists {
		return nil, fmt.Errorf("进程组 %s 不存在", groupName)
	}

	return pgm.GenerateGroupMembers(group), nil
}

// expandPattern 扩展模式字符串，支持 %d 和 %s 替换
func (pgm *ProcessGroupManager) expandPattern(pattern, memberName string) string {
	if pattern == "" {
		return pattern
	}

	// 提取成员名称中的数字部分（用于 %d 替换）
	// 从右到左查找，找到最后一个连续的数字序列
	var number string
	for i := len(memberName) - 1; i >= 0; i-- {
		char := memberName[i]
		if char >= '0' && char <= '9' {
			number = string(char) + number
		} else if number != "" {
			// 遇到非数字字符且已经有数字了，停止
			break
		}
	}

	// 替换 %d 为数字
	if number != "" {
		pattern = strings.ReplaceAll(pattern, "%d", number)
	}

	// 替换 %s 为成员名称
	pattern = strings.ReplaceAll(pattern, "%s", memberName)

	return pattern
}
